<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { Cooperation } from '@/api/modules/cooperation'
import type { FormInstance, FormRules } from 'element-plus'
import baiduApi from '@/api/modules/baiduTransApi'
import api from '@/api/modules/cooperation'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  cooperateId: route.params.id as string | number ?? '',
  ip: '',
  ipEn: '',
  cooperateName: '',
  cooperateNameEn: '', // 合作方英文名称
  contact: 0, // 允许为空，等待接口赋值
  describ: '', // 详细信息
  describEn: '', // 详细信息英文
  phonenumber: '', // 联系方式
  roleKey: '', //  角色权限字符串
  userId: '', //  数据所有者id
  uid: '', // 当前登录用户id
})
// 判断是否是编辑模式且当前用户是数据所有者
const isEdit = computed(() => {
  const isEditMode = form.value.cooperateId !== ''
  const isOwner = form.value.userId && form.value.uid && form.value.userId === form.value.uid

  // 如果是编辑模式，则必须同时是所有者才能编辑
  return !(isEditMode ? isOwner : true)
})

// 特殊字符检验
const validateNoSpecialChars = (value: string) => {
  // 允许字母、数字、汉字、空格、基本标点和中英文逗号，以及 - _ .
  return /[#$%&?]/.test(value) // 移除了 - _ .
}

// 百度翻译接口
const translateText = async (text: string, from: string, to: string): Promise<string> => {
  try {
    const response = await baiduApi.translate({
      query: text,
      from,
      to,
    })
    const data = response.data
    return data.trans_result[0].dst
  }
  catch (error) {
    console.error('Translation failed:', error)
    ElMessage.error('翻译失败，请稍后再试')
    return ''
  }
}

const translateToEnglish = async (text: string): Promise<string> => {
  return translateText(text, 'zh', 'en')
}

const translateCooperateNameToEnglish = async () => {
  if (form.value.cooperateName && form.value.cooperateName.trim() !== '') {
    form.value.cooperateNameEn = await translateToEnglish(form.value.cooperateName)
  }
}

const translateIpToEnglish = async () => {
  if (form.value.ip && form.value.ip.trim() !== '') {
    form.value.ipEn = await translateToEnglish(form.value.ip)
  }
}

const formRules = ref<FormRules>({
  ip: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    { max: 20, message: '地址长度不能超过20个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  cooperateName: [
    { required: true, message: '请输入合作方名称', trigger: 'blur' },
    { max: 20, message: '合作方名称长度不能超过20个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  describ: [
    { required: true, message: '请输入详细信息', trigger: 'blur' },
    { max: 200, message: '详细信息长度不能超过200个字符', trigger: 'blur' },
  ],
  phonenumber: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => { // 添加下划线表示忽略
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(value)) {
          callback(new Error('电话号码格式不正确'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

// 特殊控制"是否联系"开关（仅admin可编辑）
const isContactEditable = computed(() => {
  // 假设只有 roleKey 为 'admin' 时可编辑,['admin']为可配置的角色列表
  return ['admin'].includes(form.value.roleKey)
})

onMounted(() => {
  if (form.value.cooperateId !== '') {
    getInfo()
  }
})

function getInfo() {
  loading.value = true
  const cooperateId = form.value?.cooperateId
  if (cooperateId) {
    const idNumber = Number(cooperateId)
    api.detail(idNumber).then((res: any) => {
      loading.value = false
      const data = res.data.data // 提取数据
      // 完整映射所有字段
      form.value.cooperateId = data.cooperateId
      form.value.ip = data.ip
      form.value.ipEn = data.ipEn
      form.value.cooperateName = data.cooperateName
      form.value.cooperateNameEn = data.cooperateNameEn
      form.value.contact = data.contact
      form.value.describ = data.describ
      form.value.describEn = data.describEn
      form.value.phonenumber = data.phonenumber
      form.value.roleKey = data.roleKey
      form.value.userId = data.userId
      form.value.uid = data.uid
    })
  }
}

function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        // 构造符合 Cooperation 接口的对象
        const cooperationData = {
          cooperateId: Number(form.value.cooperateId),
          cooperateName: form.value.cooperateName,
          cooperateNameEn: form.value.cooperateNameEn,
          ip: form.value.ip,
          ipEn: form.value.ipEn,
          contact: form.value.contact,
          describ: form.value.describ,
          describEn: form.value.describEn,
          phonenumber: form.value.phonenumber,
        } as Cooperation
        if (form.value.cooperateId === '') {
          api.create(cooperationData).then(() => {
            ElMessage.success({
              message: '新增成功',
            })
            goBack()
          })
        }
        else {
          form.value.cooperateId = Number(form.value.cooperateId)
          api.edit(cooperationData).then(() => {
            ElMessage.success({
              message: '编辑成功',
            })
            goBack()
          })
        }
      }
    })
  })
}
function onCancel() {
  goBack()
}
// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'cooperationList' })
  }
  else {
    router.push({ name: 'cooperationList' })
  }
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'cooperationCreate' ? '新增合作' : '编辑合作'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm ref="formRef" :model="form" :rules="formRules" label-width="130px" label-suffix="：" class="custom-form">
      <FaLayoutContainer right-side-width="500px" hide-right-side-toggle class="static" right-side-class="flex flex-col">
        <ElFormItem label="来源地址" prop="ip">
          <ElInput v-model="form.ip" placeholder="请输入地址" maxlength="20" show-word-limit :disabled="isEdit" @blur="translateIpToEnglish" />
        </ElFormItem>
        <ElFormItem label="合作方名称" prop="cooperateName">
          <ElInput v-model="form.cooperateName" placeholder="请输入合作方名称" maxlength="20" show-word-limit :disabled="isEdit" @blur="translateCooperateNameToEnglish" />
        </ElFormItem>
        <ElFormItem label="联系方式" prop="phonenumber">
          <ElInput v-model="form.phonenumber" placeholder="请输入电话号码" :disabled="isEdit" />
        </ElFormItem>
        <ElFormItem v-if="!(route.name === 'cooperationCreate')" label="是否联系" prop="contact">
          <ElSwitch
            v-model="form.contact"
            :active-value="1"
            :inactive-value="0"
            :disabled="!isContactEditable"
            active-text="是"
            inactive-text="否"
            inline-prompt
          />
        </ElFormItem>

        <FaFixedActionBar>
          <ElButton type="primary" size="large" @click="onSubmit">
            提交
          </ElButton>
          <ElButton size="large" @click="onCancel">
            取消
          </ElButton>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.custom-form {
  display: flex;
  flex: 1;
  overflow: auto;
}
</style>
